
#include "core/engine.h"
#include "core/game.h"
#include "core/scene.h"

Game::Game(QObject* pkParent)
    : QObject(pkParent),
      m_bIsRunning(false),
      m_uiCowCount(0),
      m_uiShots(0),
      m_uiMatches(0)
{
}

Game::~Game()
{
}

bool Game::isRunning() const
{
    return m_bIsRunning;
}

quint32 Game::score() const
{
    return m_uiCowCount * 1000 / elapsed() / shots();
}

quint32 Game::elapsed() const
{
    if(m_bIsRunning)
        return m_kStartTime.secsTo(QTime::currentTime());
    else
        return m_kStartTime.secsTo(m_kStopTime);
}

quint32 Game::shots() const
{
    return m_uiShots;
}

quint32 Game::cowCount() const
{
    return m_uiCowCount;
}

void Game::addMatch()
{
    ++m_uiMatches;

    // Matching sound.
    FMOD_RESULT kResult;
    FMOD_EVENT* pkFMODEventMatch;
    kResult = FMOD_EventSystem_GetEvent(Engine::instance().fmod(), "melomaniac/melomaniac/match", FMOD_EVENT_DEFAULT, &pkFMODEventMatch);
    Q_ASSERT(kResult == FMOD_OK);
    kResult = FMOD_Event_Start(pkFMODEventMatch);
    Q_ASSERT(kResult == FMOD_OK);

    // Check if game is over.
    if(m_uiMatches == m_uiCowCount / 2)
    {
        m_bIsRunning = false;
        m_kStopTime = QTime::currentTime();

        // Gameover sound.
        FMOD_EVENT* pkFMODEventGameOver;
        kResult = FMOD_EventSystem_GetEvent(Engine::instance().fmod(), "melomaniac/melomaniac/gameover", FMOD_EVENT_DEFAULT, &pkFMODEventGameOver);
        Q_ASSERT(kResult == FMOD_OK);
        kResult = FMOD_Event_Start(pkFMODEventGameOver);
        Q_ASSERT(kResult == FMOD_OK);

        emit gameOver();
    }
}

void Game::addShot()
{
    ++m_uiShots;
}

void Game::start()
{
    m_bIsRunning = true;

    m_kStartTime = QTime::currentTime();
    Engine::instance().scene().setup();
}

void Game::clear()
{
    m_uiCowCount = 0;
    m_uiShots = 0;
    m_uiMatches = 0;
}

void Game::setDifficulty(int iIndex)
{
    Q_ASSERT(iIndex >= 0 && iIndex < 3);

    switch(iIndex)
    {
    case 0:
        m_uiCowCount = 6;
        break;

    case 1:
        m_uiCowCount = 10;
        break;

    case 2:
        m_uiCowCount = 12;
        break;
    }
}
